#!/usr/bin/php
<?php
/**
 *
 * Omniture Twitter Analytics is PHP script that uses the Twitter API and Omniture
 * Data Insertion API to put tweets directly into an Omniture Report Suite. This allows
 * Twitter analytics to be analyzed right next to website data. 
 * 
 * more information at:
 *  http://code.google.com/p/omniture-twitter-analytics/
 *  http://omnituretwitteranalytics.com/
 * 
 * @id $Id: omniture-twitter-analytics.php 13 2010-04-01 02:37:06Z hopperab $
 * @author Jason Thompson (jthomp@gmail.com)
 * @author Andrew Hopper (hopperab@gmail.com)
 * 
 * @todo get user location and store in prop
 * 
 * @license GNU General Public License v3
 * 
 */

# == CONFIGURATION VARIABLES ==

$debug_mode = false;

// Twitter Search API Search Parameters
// Configure your Twitter searches here
$queries["term: ipad"] = "+iPad";
$queries["@THE_REAL_SHAQ"] = "@THE_REAL_SHAQ"; //tweets to shaq
$queries["term: iphone"] = "+iphone";

// you can add unlimited searches here, they should be added in the format
// $queries["human readable label"] = "search terms passed to Omniture"

/** Omniture Data Insertion API Parameters */
$omniture_rsid = "<insert your report suite id here>";	// report suite id
$omniture_dc = "<insert your Omniture data center here>";		// 112 is Dallas, 124 is San Diego (I think)

# DO NOT ALTER ANYTHING BELOW THIS LINE ################

// average number of followers
// http://www.guardian.co.uk/technology/blog/2009/jun/29/twitter-users-average-api-traffic
$average_num_followers_per_twitter_user = "126";

// Twitter will return a max of 1500 most recent search results 
$max_tweets_per_query = "50";

// when grouping tweets based on number of followers the author has use this bucket size
$bucket_size = 50;

if(file_exists(dirname(__FILE__)."/config.php"))
{
	// override the config options above
	include(dirname(__FILE__)."/config.php");
}

/** Data Cache Directory **/
$cache_dir = dirname(__FILE__)."/data";

/** Include the Offical Omniture PHP Measurement library **/
require_once 'OmnitureMeasurement.class.php';

if($debug_mode)
{
	echo "=== DEBUG MODE ======================================================\n";
	echo "  In debug_mode no calls are actually sent to Omniture.  Please\n";
	echo "  change ";
	echo '$debug_mode=false in the config to send data to Omniture'."\n";
	echo "========================================================================\n\n";
	// override the max tweets per page var in debug mode
	// this speeds up testing
	$max_tweets_per_query = 5;
}
else
{
	if($omniture_rsid == "<insert your report suite id here>")
	{
		echo "ERROR: you must configure your report suite id on line 35\n";
		exit;
	}
	if($omniture_dc == "<insert your Omniture data center here>")
	{
		echo "ERROR: you must configure your Omniture datacenter on line 36\n";
		exit;
	}
}

foreach($queries as $tweetSearchName=>$q)
{
	// remove @, ":", and other invalid characters from the search name
	// so we can generate a valid filename for this search
	$searchId = preg_replace("/[^a-zA-Z0-9\s]/", "", $tweetSearchName);
	
	/** most recent tweet id is stored in twitid.txt; used to grab only new tweets since last script execution */
	$twitIdFile = $cache_dir."/"."$searchId.txt";
	
	if(file_exists($twitIdFile))
	{
		// read the status_id of the most recent tweet for this search
		$fh = fopen($twitIdFile, 'r');
		$twitSinceId = fread($fh, filesize($twitIdFile));
		fclose($fh);
		unset($fh);
		$s=$twitSinceId;
	}
	else
	{
		// this is a virgin run for this search
		// get all the tweets to the limit of 
		// max_tweets_per_query
		$twitSinceId = "";
	}
	
	// ------- START --------

	/** call Twitter Search API.  Required Parameters: 
	$rpp=max search results to return.  defined in omtrTwitConfig.php
	$since_id=id of last tweet processed.  returned from twitid.txt
	$q=search terms.  defined in omtrTwitConfig.php
*/
	$search = "http://search.twitter.com/search.atom?rpp=".$max_tweets_per_query;
	
	// if the status_id of the most recent tweet is set then use this to only
	// query for tweets since the last sucessful run of this script
	if($twitSinceId) $search .= "&since_id=".$s;
	$search .= "&q=".urlencode($q)."";
	
	/* connect to Twitter Search API and process results using SimpleXMLElement
	REQUIRES: PHP5 */	
	$twi = implode("",file($search));
	$search_res = new SimpleXMLElement($twi);
	
	echo "\n**** Twitter search results for '".$q."' ****\n";
	echo "query: $search"."\n\n";
	
	$most_recent_tweet = true;
	
	if(count($search_res->entry) > 0)
	{
		/* step through Twitter results */
		foreach ($search_res->entry as $i=>$twit1) {

			// parse the tweet
			$twit_id = explode(":", $twit1->id);
			$wTwitId = $twit_id[2];
			$pageURL = $twit1->link["href"];
			
			$tweet_timestamp = $twit1->published;
			
			//capture twitter values for insertion
			//HTML tags must be stripped from the content or they will fail to be loaded into Omniture variables
			$tweetAuthor = strip_tags($twit1->author->name);
			$tweetContent = strip_tags($twit1->content);
			$dt_published = $twit1->published;
		
			// the atom feed for the search results returns authors in the format
			// Nice Name (screename), this parse the link to the twitter profile
			// so we can get the username for user in further queries
			$twitter_username = str_replace("http://twitter.com/","",$twit1->author->uri);
		
			// call the Twitter API for the user's profile
			$profile_info = get_profile_info($twitter_username);
			$followers = $profile_info->followers_count;
			$time_zone = $profile_info->time_zone;
			$location = $profile_info->location;
			$language = $profile_info->lang;
			$utc_offset = $profile_info->utc_offset;
			$created_at = $profile_info->created_at; 
			
			// output debugging information
			echo "==Tweet for search '$q'==\n";
			echo strip_tags($twit1->content)."\n";
			echo "Author: ".$twit1->author->name."\n";
			echo "Tweet ID: $twit_id[2]\n";
			echo "Published: ".$twit1->published."\n";
			echo "Followers: ".$followers."\n";
			echo "Time Zone: ".$time_zone."\n";
			echo "Language: ".$language."\n";
			echo "Location: ".$location."\n";
		
			/* if tweet is the most recent tweet, grab id and write to twitid.txt.  */ 	
			if ($most_recent_tweet) {
	  			$fh = fopen($twitIdFile, 'w') or die("can't open file");
				fwrite($fh, $wTwitId);
				fclose($fh);
				unset($fh);	
				//echo "writing twitID $wTwitId to file $twitIdFile";
				$most_recent_tweet = false;
			}
		
			// send the tweet to Omniture
			$s = new OmnitureMeasurement();

			/* Specify the Report Suite ID(s) to track here */
			$s->account = $omniture_rsid;
			$s->dc = $omniture_dc;

			/* Turn on and configure debugging here */
			$s->debugTracking = true;

			$s->channel = $tweetSearchName;
			
			$s->pageName = $tweetContent;
			$s->pageURL = $pageURL;

			$s->eVar1 = $tweetAuthor;
			$s->prop1 = $tweetAuthor;

			$s->eVar2 = $tweetContent;
			$s->prop2 = $tweetContent;

			$s->eVar3 = $tweetSearchName;
			$s->prop3 = $tweetSearchName;

			$s->eVar4 = $q;
			$s->prop4 = $q;

			$s->eVar5 = $dt_published;
			$s->prop5 = $dt_published;

			$s->eVar6 = $followers;
			$s->prop6 = $s->eVar6;

			$s->eVar7 = $twitter_username;
			$s->prop7 = $s->eVar7;
			
			$s->eVar8 = round($followers/$average_num_followers_per_twitter_user,2);
			$s->prop8 = $s->eVar8;
			
			$s->eVar9 = $average_num_followers_per_twitter_user;
			$s->prop9 = $s->eVar9;
			
			// twitter profile timezone
			$s->eVar10 = $time_zone;
			$s->prop10 = $s->eVar10;
			
			// language per twitter profile
			$s->eVar11 = $language;
			$s->prop11 = $s->eVar11;
			
			// bucket for number of followers (0-50,51-100,etc)
			$s->eVar12 = (floor($followers/$bucket_size)*$bucket_size)." to ".((floor($followers/$bucket_size)*$bucket_size)+$bucket_size-1);
			$s->prop12 = (floor($followers/$bucket_size)*$bucket_size)." to ".((floor($followers/$bucket_size)*$bucket_size)+$bucket_size-1);
			
			// location of twitter user
			$s->eVar13 = $location;
			$s->prop13 = $location;
			
			// timezone of twitter profile
			$s->eVar14 = $time_offset;
			$s->eVar14 = $time_offset;
		
			// date the twitter account was created
			$s->evar15 = $created_at;
			$s->prop15 = $created_at;
			
			$s->events = "event1";
			
			$s->timestamp = date('j/',strtotime($tweet_timestamp)) . (date('n',strtotime($tweet_timestamp)) - 1) . 
							date('/Y H:i:s w ',strtotime($tweet_timestamp)) . (date('Z',strtotime($tweet_timestamp)) / -60);
			
			$s->sendFromServer = true;
		
			$s->track();
		
			unset($s);

		}
	}
	else
	{
		echo "no new tweets found since tweet with status_id $s\n";
	}
}

function get_profile_info($screen_name)
{
	$url = 'http://api.twitter.com/1/users/show.xml?screen_name='.$screen_name;
	echo $url;
	$profile_info = implode(@file($url)) or die("failed to fetch user profile info for ".$screen_name);
	$profile_object = new SimpleXMLElement($profile_info);
	return $profile_object;
}
